package com.kj.platformlogistics.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import com.kj.platformlogistics.R;


public class MyRelativeLayout extends RelativeLayout {

    private float WidthFloat;
    private float HighFloat;
    private Boolean ChangeWidth;

    public MyRelativeLayout(Context context) {
        super(context);
    }

    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyRelativeLayout);
        WidthFloat = typedArray.getFloat(R.styleable.MyRelativeLayout_Width_Ratio, 0);
        HighFloat = typedArray.getFloat(R.styleable.MyRelativeLayout_High_Ratio, 0);
        ChangeWidth = typedArray.getBoolean(R.styleable.MyRelativeLayout_Change_Width, false);
    }

    public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyRelativeLayout, defStyleAttr, 0);

        WidthFloat = typedArray.getFloat(R.styleable.MyRelativeLayout_Width_Ratio, 0);
        HighFloat = typedArray.getFloat(R.styleable.MyRelativeLayout_High_Ratio, 0);
        ChangeWidth = typedArray.getBoolean(R.styleable.MyRelativeLayout_Change_Width, false);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        if (WidthFloat != 0 && HighFloat != 0) {
            if (ChangeWidth) {
                widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) (MeasureSpec.getSize(heightMeasureSpec) / HighFloat * WidthFloat), MeasureSpec.EXACTLY);
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            } else {
                heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (MeasureSpec.getSize(widthMeasureSpec) / WidthFloat * HighFloat), MeasureSpec.EXACTLY);
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        } else {
            //必须调用下面的两个方法之一完成onMeasure方法的重写，否则会报错
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
